package com.zsy._04volatile关键字深入学习;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * volatile 不保证原子性
 *
 * @author: zhangshuaiyin
 * @date: 2021/10/4 22:33
 */
public class VolatileDemo02 {
    /**
     * volatile 不保证原子性
     */
    private volatile static int num = 0;

    public static void add() {
        num++;
    }

    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(
                2000,
                2000,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
                );
        //理论上num结果应该为 2 万
        for (int i = 1; i <= 20; i++) {
            threadPool.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            });
        }
        threadPool.shutdown();
        while (Thread.activeCount() > 2) { // main gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + " " + num);
    }
}
